package DivideAndConquer;

/**
 * 二分查找
 * @author: luo
 * @email: luo@nyist.edu.cn
 * @date: 2020/12/15 16:00
 */
public class BinarySearch {
    public static void main(String[] args) {

        int[] s = {1, 2, 3, 4, 5, 6, 7, 8, 9};
//        int num = f(s, 1, 0, 8);
        int num = f2(s, 1);

        System.out.println(num);
    }

    /**
     * 递归方式
     * @param s 有序数组
     * @param x 查找的数字
     * @param low 开始下标
     * @param high 结束下标
     * @return 下标
     */
    static int f(int[] s, int x, int low, int high) {
        if (low > high) return -1;
        int middle = (low + high) / 2;
        int num;
        if (s[middle] < x) {
            num = f(s, x, middle + 1, high);
        } else if (s[middle] > x) {
            num = f(s, x, low, middle - 1);
        } else {
            num = middle;
        }
        return num;
    }

    static int f2(int[] s, int x) {
        int low = 0;
        int high = s.length - 1;
        while (low <= high) {
            int middle = (low + high) / 2;
            if (x == s[middle]) {
                return middle;
            } else if (x > s[middle]) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }
        }
        return -1;
    }
}
